package com.aop.service;

import com.aop.main.mainimpl.MyMainImpl;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;

import java.beans.beancontext.BeanContextProxy;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

public class MyService implements BeanPostProcessor, ApplicationContextAware {
    private ApplicationContext applicationContext;
    @Override
    public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
        if(bean.getClass().getPackage().getName().equals("com.aop.advice.impl")){
            Object BeanProxy = Proxy.newProxyInstance(
                    bean.getClass().getClassLoader(),
                    bean.getClass().getInterfaces(),
                    (Object proxy, Method method, Object[] args) -> {
                        MyMainImpl myMain = applicationContext.getBean("myMain", MyMainImpl.class);
                        myMain.show1();
                        Object result = method.invoke(bean, args);
                        myMain.show2();
                        return result;
                    }
            );
            return BeanProxy;
        }
        return bean;
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.applicationContext=applicationContext;
    }
}
